package cn.alexy.dbbench.server.service;

import cn.alexy.dbbench.server.entity.Pi;
import cn.alexy.dbbench.server.entity.Result;
import cn.alexy.dbbench.server.repository.PiDao;
import cn.alexy.dbbench.server.repository.ResultDao;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springside.modules.utils.DateProvider;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import cn.alexy.dbbench.server.service.account.ShiroDbRealm.ShiroUser;

/**
 * DB Bench 业务处理
 *
 * @author alexy
 */
// Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class DBBenchService {

    private static Logger logger = LoggerFactory
            .getLogger(DBBenchService.class);
    private final RestTemplate restTemplate = new RestTemplate();

    private static String resoureUrl = "http://localhost:8080/server/api/v1/benchresult";

    private PiDao piDao;
    private ResultDao resultDao;
    // private ResultDao resultDao;
    private Result result;
    private DateProvider dateProvider = DateProvider.DEFAULT;
    
    private  MongoDatabase db = null;
    
    private com.mongodb.MongoClient mongoClient = null;

    public DBBenchService() {
        // this.result = new Result();
        // this.result.setBenchdate(new Date());
    }

    public Result getResult() {
        return this.result;
    }

    public void saveResult(){
     resultDao.save(this.result);
    }
    
    public void saveResultByRest() {
        this.result.setBenchdate(new Date());
        System.out.println(this.result);
        String str = restTemplate.postForObject(resoureUrl, this.result,
                String.class, 0);
        System.out.println(str);
    }

    public void saveResultToNoSQL() {

        this.result.setBenchdate(new Date());
        System.out.println(this.result);
        
        mongoClient=new MongoClient("127.0.0.1:27017");  
        db=mongoClient.getDatabase("bench"); 
        
        MongoCollection<Document> peoples=db.getCollection("result");  
        Document doc=new Document();  
        doc.put("Adapter", this.result.getAdapter());  
        doc.put("toString", this.result.toString());  
        doc.put("BenchDate", this.result.getBenchdate());  


        peoples.insertOne(doc);  
        
        MongoCollection<Document> collec=db.getCollection("result");  
        System.out.println(collec);  
        MongoCursor<Document> cursor=collec.find().iterator();  
        while(cursor.hasNext()){  
            Document obj=(Document)cursor.next();  
            System.out.println(obj.get("Adapter")+","+obj.get("BenchDate"));  
        }  

    }

    public List<Pi> getAllDate() {
        return (List<Pi>) piDao.findAll();
    }

    @Record
    @Transactional(readOnly = false)
    public void fillData(List<Pi> items) {
        // logger.info("开始加载数据……");

        // logger.info("加载数据完成。");
        // logger.info("开始保存数据……");
        this.piDao.save(items);
        this.piDao.flush();
        // logger.info("保存数据完成。");

    }

    @Record
    @Transactional(readOnly = false)
    public void editData() {
        Date t1 = new Date();
        List<Pi> items = (List<Pi>) this.piDao.findAll();
        Date t2 = new Date();
        System.out.println(t2.getTime() - t1.getTime());

        for (Pi item : items) {
            item = this.piChanger(item);
        }
        this.piDao.save(items);
        this.piDao.flush();
    }

    @Record
    @Transactional(readOnly = false)
    public void delData() {
        this.piDao.deleteAll();
        this.piDao.flush();
    }

    @Record
    @Transactional(readOnly = false)
    public void emptyData() {
        this.piDao.deleteAllInBatch();
        this.piDao.flush();
    }

    @Record
    public void sumData() {
        List<SumTemp> l;
        l = this.piDao.runQuery();
        for (SumTemp tmp : l) {
			System.out.println(tmp.toString());
//            tmp.toString();
        }

    }

    @Record
    public void queryData() {

        Page<Pi> items;
        for (int i = 0; i < this.getResult().getDatacount() / 100; i++) {

            Sort sort = new Sort(Direction.DESC, "icol");
            PageRequest page = new PageRequest(i, 100, sort);

            items = (Page<Pi>) this.piDao.findAll(page);
			System.out.println("Page:" + i + "-" + items.getSize());
//			for (Pi item : items) {
//				// System.out.println(item);
//			}
        }
    }

    @Record
    @Transactional(readOnly = false)
    public long getCount() {
        return this.piDao.count();
    }

    @Record
    public List<Pi> loadtoMem(int count) {
        List<Pi> items = new ArrayList<Pi>(count);

        try {
            System.out.println(System.getProperty("user.dir"));
            BufferedReader in = new BufferedReader(new FileReader(new File(
                    "pi_data.txt")));
            String line;
            while ((line = in.readLine()) != null) {
                String[] str = line.split(" ");
                for (int i = 0; i < str.length; i++) {
                    if (str[i].length() != 10) {
                        continue;
                    }
                    items.add(this.piMaker(items.size(), str[i]));
                    if (items.size() >= count) {
                        return items;
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return items;

    }

    private Pi piMaker(int i, String s) {
        Pi item = new Pi(i);
        item.setScol(s);
        item.setIcol(Long.parseLong(s));
        item.setDcol(Double.parseDouble(s) / 100);
        item.setDtcreat(dateProvider.getDate());
        return item;
    }

    private Pi piChanger(Pi item) {
        item.setScol(new StringBuffer(item.getScol()).reverse().toString());
        item.setDcol(item.getDcol() / 100);
        item.setDtcreat(dateProvider.getDate());
        return item;
    }

    @Autowired
    public void setPiDao(PiDao piDao) {
        this.piDao = piDao;
    }

    @Autowired
    public void setResul(Result result) {
        this.result = result;
    }

    public void setDateProvider(DateProvider dateProvider) {
        this.dateProvider = dateProvider;
    }
}
